package study.mybatis.multi.datasource.support.mybatisplus;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@MapperScan(basePackages = "study.mybatis.multi.datasource.mapper.user", sqlSessionFactoryRef = "userSqlSessionFactory")
@MapperScan(basePackages = "study.mybatis.multi.datasource.mapper.account", sqlSessionFactoryRef = "accountSqlSessionFactory")
@Configuration
public class MybatisPlusConfig {

    @Primary
    @Bean("userSqlSessionFactory")
    public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource ds) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();

        //数据源
        factoryBean.setDataSource(ds);
        //mapper文件
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("study/mybatis/multi/datasource/mapper/user/**.xml"));
        //类别名
        factoryBean.setTypeAliasesPackage("study.mybatis.multi.datasource.mapper.user");

        //
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setBanner(false);
        factoryBean.setGlobalConfig(globalConfig);

        return factoryBean.getObject();
    }

    @Bean("accountSqlSessionFactory")
    public SqlSessionFactory accountSqlSessionFactory(@Qualifier("accountDataSource") DataSource ds) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(ds);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("study/mybatis/multi/datasource/mapper/account/**.xml"));
        factoryBean.setTypeAliasesPackage("study.mybatis.multi.datasource.mapper.account");

        return factoryBean.getObject();
    }
}
